<template>
  <div class="salary-view4">
    <h1>Salary View 4</h1>
    <form @submit.prevent="handleSubmit">
      <div>(store双向绑定)</div>
      <div>
        <label for="name">用户姓名：</label>
        <input id="name" v-model="form.userName.value" type="text" required />
      </div>
      <div>
        <label for="salary">薪资：</label>
        <input id="salary" v-model="form.salary.value" type="number" required />
      </div>
      <button type="submit">提交</button>
    </form>
    <div>&nbsp;</div>
    <form @submit.prevent="handleSubmit">
      <div>(获取store属性)</div>
      <div>
        <label for="name">用户姓名：</label>
        <input id="name" v-model="form2.name" type="text" required />
      </div>
      <div>
        <label for="salary">薪资：</label>
        <input id="salary" v-model="form2.salary" type="number" required />
      </div>
      <button type="submit">提交</button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import type { SalaryInfo } from '@/types/SalaryInfo'
import { userSalaryStore } from '@/store/UserSalaryStore'
import { storeToRefs } from 'pinia'

const localUserSalaryStore = userSalaryStore()

const form2 = reactive<SalaryInfo>({
  name: localUserSalaryStore.getUserName,
  salary: localUserSalaryStore.getSalary
})

// 将store对象转为ref对象，双向绑定
const form = storeToRefs(localUserSalaryStore)
console.log(form)

function handleSubmit() {
  // 这里可以处理表单提交逻辑
  console.log('提交数据:', form)

  console.log('before:'+ localUserSalaryStore.getUserName)
  // 修改store数据
  // localUserSalaryStore.$patch({
  //   userName: form.name
  // })
  localUserSalaryStore.changeUserName(form2.name)

  console.log('after:'+ localUserSalaryStore.getUserName)
}
</script>

<style scoped>
.salary-view4 {
  padding: 20px;
}
form > div {
  margin-bottom: 10px;
}
label {
  margin-right: 8px;
}
</style>
